﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SnakeGame
{
    public partial class Form1 : Form
    {
        // Windows API声明
        [DllImport("user32.dll")]
        private static extern IntPtr GetDC(IntPtr hWnd);
        
        [DllImport("user32.dll")]
        private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
        
        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateCompatibleDC(IntPtr hDC);
        
        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);
        
        [DllImport("gdi32.dll")]
        private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
        
        [DllImport("gdi32.dll")]
        private static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, 
            IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop);
        
        [DllImport("gdi32.dll")]
        private static extern bool DeleteObject(IntPtr hObject);
        
        [DllImport("gdi32.dll")]
        private static extern bool DeleteDC(IntPtr hDC);
        
        private GameController gameController;
        private GameRenderer gameRenderer;
        private Timer gameTimer;
        private Timer demoTimer;
        private bool isGameRunning = false;
        private bool isDemoMode = false;
        private Random demoRandom = new Random();
        
        // 双缓冲相关
        private BufferedGraphics bufferedGraphics;
        private BufferedGraphicsContext bufferedContext;

        public Form1()
        {
            InitializeComponent();
            InitializeGame();
        }

        /// <summary>
        /// 初始化游戏
        /// </summary>
        private void InitializeGame()
        {
            // 创建游戏控制器和渲染器
            gameController = new GameController();
            gameRenderer = new GameRenderer(gameController);

            // 设置窗体属性
            this.KeyPreview = true;
            this.DoubleBuffered = true;

            // 设置游戏面板的双缓冲和优化
            SetStyle(ControlStyles.AllPaintingInWmPaint | 
                    ControlStyles.UserPaint | 
                    ControlStyles.DoubleBuffer |
                    ControlStyles.ResizeRedraw, true);

            // 初始化高级双缓冲
            InitializeBufferedGraphics();

            // 创建游戏定时器
            gameTimer = new Timer();
            gameTimer.Interval = gameController.Config.GameSpeed;
            gameTimer.Tick += GameTimer_Tick;

            // 创建演示定时器
            demoTimer = new Timer();
            demoTimer.Interval = 200; // 演示模式稍慢一些
            demoTimer.Tick += DemoTimer_Tick;

            // 订阅游戏事件
            gameController.GameStateChanged += GameController_GameStateChanged;
            gameController.ScoreChanged += GameController_ScoreChanged;
            gameController.GameOver += GameController_GameOver;

            // 更新界面
            UpdateUI();
        }

        /// <summary>
        /// 初始化高级双缓冲
        /// </summary>
        private void InitializeBufferedGraphics()
        {
            // 获取当前图形上下文
            bufferedContext = BufferedGraphicsManager.Current;
            
            // 设置最大缓冲区大小
            bufferedContext.MaximumBuffer = new Size(gamePanel.Width + 1, gamePanel.Height + 1);
            
            // 创建缓冲区
            bufferedGraphics = bufferedContext.Allocate(gamePanel.CreateGraphics(), 
                new Rectangle(0, 0, gamePanel.Width, gamePanel.Height));
            
            // 设置高质量绘制
            bufferedGraphics.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            bufferedGraphics.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            bufferedGraphics.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        }

        /// <summary>
        /// 使用双缓冲渲染游戏
        /// </summary>
        private void RenderGame()
        {
            try
            {
                // 清除缓冲区
                bufferedGraphics.Graphics.Clear(gamePanel.BackColor);
                
                // 在缓冲区中绘制游戏
                Rectangle gameArea = new Rectangle(0, 0, gamePanel.Width, gamePanel.Height);
                gameRenderer.Draw(bufferedGraphics.Graphics, gameArea);
                
                // 使用Windows API进行高效的双缓冲复制
                IntPtr hdcDest = GetDC(gamePanel.Handle);
                IntPtr hdcSrc = bufferedGraphics.Graphics.GetHdc();
                
                // 使用SRCCOPY进行位图复制，这是最快的复制方式
                BitBlt(hdcDest, 0, 0, gamePanel.Width, gamePanel.Height, 
                       hdcSrc, 0, 0, 0x00CC0020); // SRCCOPY = 0x00CC0020
                
                // 释放资源
                bufferedGraphics.Graphics.ReleaseHdc(hdcSrc);
                ReleaseDC(gamePanel.Handle, hdcDest);
            }
            catch (Exception)
            {
                // 如果Windows API失败，回退到普通双缓冲
                try
                {
                    bufferedGraphics.Render(gamePanel.CreateGraphics());
                }
                catch
                {
                    // 如果双缓冲也失败，回退到普通绘制
                    gamePanel.Invalidate();
                }
            }
        }

        /// <summary>
        /// 游戏定时器事件
        /// </summary>
        private void GameTimer_Tick(object sender, EventArgs e)
        {
            if (gameController.State == GameState.Playing)
            {
                gameController.Update();
                // 使用双缓冲绘制，避免闪烁
                RenderGame();
            }
        }

        /// <summary>
        /// 演示定时器事件
        /// </summary>
        private void DemoTimer_Tick(object sender, EventArgs e)
        {
            if (gameController.State == GameState.Playing)
            {
                // 自动演示：随机改变方向
                AutoChangeDirection();
                gameController.Update();
                // 使用双缓冲绘制，避免闪烁
                RenderGame();
            }
        }

        /// <summary>
        /// 自动改变方向（演示模式）
        /// </summary>
        private void AutoChangeDirection()
        {
            Direction currentDirection = gameController.Snake.Direction;
            Point snakeHead = gameController.Snake.Body[0].Position;
            Point foodPosition = gameController.Food.Position;

            // 使用改进的路径寻找算法
            Direction bestDirection = FindOptimalPathToFood(snakeHead, foodPosition, currentDirection);
            
            // 如果找到有效路径，直接使用
            if (bestDirection != Direction.None)
            {
                gameController.ChangeSnakeDirection(bestDirection);
                return;
            }

            // 如果路径寻找失败，使用备用策略
            Direction[] directions = { Direction.Up, Direction.Down, Direction.Left, Direction.Right };
            Direction[] validDirections = directions.Where(d => 
                (currentDirection == Direction.Up && d != Direction.Down) ||
                (currentDirection == Direction.Down && d != Direction.Up) ||
                (currentDirection == Direction.Left && d != Direction.Right) ||
                (currentDirection == Direction.Right && d != Direction.Left)
            ).ToArray();

            // 寻找安全的方向
            List<Direction> safeDirections = new List<Direction>();
            foreach (Direction dir in validDirections)
            {
                Point nextPosition = GetNextPosition(snakeHead, dir);
                if (IsSafeMove(nextPosition, dir))
                {
                    safeDirections.Add(dir);
                }
            }

            if (safeDirections.Count > 0)
            {
                // 在安全方向中选择最接近食物的方向
                Direction bestSafeDirection = safeDirections[0];
                int bestDistance = int.MaxValue;

                foreach (Direction dir in safeDirections)
                {
                    Point nextPosition = GetNextPosition(snakeHead, dir);
                    int distance = Math.Abs(nextPosition.X - foodPosition.X) + Math.Abs(nextPosition.Y - foodPosition.Y);
                    if (distance < bestDistance)
                    {
                        bestDistance = distance;
                        bestSafeDirection = dir;
                    }
                }

                gameController.ChangeSnakeDirection(bestSafeDirection);
            }
        }

        /// <summary>
        /// 寻找最佳方向到食物
        /// </summary>
        private Direction FindBestDirectionToFood(Direction[] validDirections)
        {
            Point snakeHead = gameController.Snake.Body[0].Position;
            Point foodPosition = gameController.Food.Position;
            Direction currentDirection = gameController.Snake.Direction;

            // 计算到食物的距离
            int distanceToFood = Math.Abs(snakeHead.X - foodPosition.X) + Math.Abs(snakeHead.Y - foodPosition.Y);

            // 优化：优先保持当前方向，减少不必要的改变
            if (IsSafeMove(GetNextPosition(snakeHead, currentDirection), currentDirection))
            {
                // 如果当前方向安全，检查是否朝向食物
                Point nextPosition = GetNextPosition(snakeHead, currentDirection);
                if (IsCloserToFood(nextPosition, foodPosition, snakeHead) || distanceToFood > 5)
                {
                    // 如果当前方向朝向食物或食物较远，保持当前方向
                    return currentDirection;
                }
            }

            // 如果食物很近（≤3格），优先选择直接朝向食物的方向
            if (distanceToFood <= 3)
            {
                foreach (Direction dir in validDirections)
                {
                    Point nextPosition = GetNextPosition(snakeHead, dir);
                    if (IsSafeMove(nextPosition, dir) && IsCloserToFood(nextPosition, foodPosition, snakeHead))
                    {
                        return dir;
                    }
                }
            }

            // 否则，选择不会立即导致碰撞的方向
            List<Direction> safeDirections = new List<Direction>();
            foreach (Direction dir in validDirections)
            {
                Point nextPosition = GetNextPosition(snakeHead, dir);
                if (IsSafeMove(nextPosition, dir))
                {
                    safeDirections.Add(dir);
                }
            }

            if (safeDirections.Count > 0)
            {
                // 在安全方向中选择最接近食物的方向
                Direction bestDirection = safeDirections[0];
                int bestDistance = int.MaxValue;

                foreach (Direction dir in safeDirections)
                {
                    Point nextPosition = GetNextPosition(snakeHead, dir);
                    int distance = Math.Abs(nextPosition.X - foodPosition.X) + Math.Abs(nextPosition.Y - foodPosition.Y);
                    if (distance < bestDistance)
                    {
                        bestDistance = distance;
                        bestDirection = dir;
                    }
                }

                return bestDirection;
            }

            // 如果没有安全方向，保持当前方向
            return currentDirection;
        }

        /// <summary>
        /// 寻找到食物的最优路径（使用改进的路径寻找算法）
        /// </summary>
        private Direction FindOptimalPathToFood(Point snakeHead, Point foodPosition, Direction currentDirection)
        {
            // 如果蛇头已经在食物位置，不需要移动
            if (snakeHead == foodPosition)
                return Direction.None;

            // 计算到食物的曼哈顿距离
            int distanceToFood = Math.Abs(snakeHead.X - foodPosition.X) + Math.Abs(snakeHead.Y - foodPosition.Y);

            // 如果食物很近（≤2格），使用直接路径
            if (distanceToFood <= 2)
            {
                return FindDirectPathToFood(snakeHead, foodPosition, currentDirection);
            }

            // 使用改进的路径寻找算法
            return FindSmartPathToFood(snakeHead, foodPosition, currentDirection);
        }

        /// <summary>
        /// 寻找直接路径到食物（适用于食物很近的情况）
        /// </summary>
        private Direction FindDirectPathToFood(Point snakeHead, Point foodPosition, Direction currentDirection)
        {
            Direction[] directions = { Direction.Up, Direction.Down, Direction.Left, Direction.Right };
            
            // 优先选择直接朝向食物的方向
            if (snakeHead.X < foodPosition.X && IsSafeMove(GetNextPosition(snakeHead, Direction.Right), Direction.Right))
                return Direction.Right;
            if (snakeHead.X > foodPosition.X && IsSafeMove(GetNextPosition(snakeHead, Direction.Left), Direction.Left))
                return Direction.Left;
            if (snakeHead.Y > foodPosition.Y && IsSafeMove(GetNextPosition(snakeHead, Direction.Up), Direction.Up))
                return Direction.Up;
            if (snakeHead.Y < foodPosition.Y && IsSafeMove(GetNextPosition(snakeHead, Direction.Down), Direction.Down))
                return Direction.Down;

            // 如果直接路径不可用，选择安全的方向
            foreach (Direction dir in directions)
            {
                if (dir != GetOppositeDirection(currentDirection) && IsSafeMove(GetNextPosition(snakeHead, dir), dir))
                    return dir;
            }

            return Direction.None;
        }

        /// <summary>
        /// 寻找智能路径到食物（适用于食物较远的情况）
        /// </summary>
        private Direction FindSmartPathToFood(Point snakeHead, Point foodPosition, Direction currentDirection)
        {
            Direction[] directions = { Direction.Up, Direction.Down, Direction.Left, Direction.Right };
            List<Direction> safeDirections = new List<Direction>();

            // 收集所有安全的方向
            foreach (Direction dir in directions)
            {
                if (dir != GetOppositeDirection(currentDirection))
                {
                    Point nextPosition = GetNextPosition(snakeHead, dir);
                    if (IsSafeMove(nextPosition, dir))
                    {
                        safeDirections.Add(dir);
                    }
                }
            }

            if (safeDirections.Count == 0)
                return Direction.None;

            // 如果只有一个安全方向，直接使用
            if (safeDirections.Count == 1)
                return safeDirections[0];

            // 评估每个方向的价值
            Direction bestDirection = safeDirections[0];
            int bestScore = int.MinValue;

            foreach (Direction dir in safeDirections)
            {
                Point nextPosition = GetNextPosition(snakeHead, dir);
                int score = EvaluateDirection(nextPosition, foodPosition, dir, currentDirection);
                
                if (score > bestScore)
                {
                    bestScore = score;
                    bestDirection = dir;
                }
            }

            return bestDirection;
        }

        /// <summary>
        /// 评估方向的价值
        /// </summary>
        private int EvaluateDirection(Point nextPosition, Point foodPosition, Direction newDirection, Direction currentDirection)
        {
            int score = 0;

            // 距离食物的评分（越近越好）
            int distanceToFood = Math.Abs(nextPosition.X - foodPosition.X) + Math.Abs(nextPosition.Y - foodPosition.Y);
            score -= distanceToFood * 10;

            // 保持当前方向的奖励（减少不必要的转向）
            if (newDirection == currentDirection)
                score += 5;

            // 朝向食物的奖励
            if (IsCloserToFood(nextPosition, foodPosition, GetNextPosition(nextPosition, GetOppositeDirection(newDirection))))
                score += 15;

            // 避免死胡同的惩罚
            if (IsDeadEnd(nextPosition))
                score -= 50;

            // 长蛇安全性奖励（优先选择更安全的移动）
            if (gameController.Snake.Body.Count > 5)
            {
                if (IsMoveSafeForLongSnake(nextPosition, newDirection))
                    score += 20;
                else
                    score -= 30; // 对不安全的移动进行惩罚
            }

            return score;
        }

        /// <summary>
        /// 检查位置是否是死胡同
        /// </summary>
        private bool IsDeadEnd(Point position)
        {
            Direction[] directions = { Direction.Up, Direction.Down, Direction.Left, Direction.Right };
            int safeDirections = 0;

            foreach (Direction dir in directions)
            {
                Point nextPos = GetNextPosition(position, dir);
                if (IsSafeMove(nextPos, dir))
                    safeDirections++;
            }

            return safeDirections <= 1;
        }

        /// <summary>
        /// 获取相反方向
        /// </summary>
        private Direction GetOppositeDirection(Direction direction)
        {
            switch (direction)
            {
                case Direction.Up: return Direction.Down;
                case Direction.Down: return Direction.Up;
                case Direction.Left: return Direction.Right;
                case Direction.Right: return Direction.Left;
                default: return Direction.None;
            }
        }

        /// <summary>
        /// 获取下一个位置
        /// </summary>
        private Point GetNextPosition(Point currentPosition, Direction direction)
        {
            switch (direction)
            {
                case Direction.Up:
                    return new Point(currentPosition.X, currentPosition.Y - 1);
                case Direction.Down:
                    return new Point(currentPosition.X, currentPosition.Y + 1);
                case Direction.Left:
                    return new Point(currentPosition.X - 1, currentPosition.Y);
                case Direction.Right:
                    return new Point(currentPosition.X + 1, currentPosition.Y);
                default:
                    return currentPosition;
            }
        }

        /// <summary>
        /// 检查移动是否有效（不会撞墙或撞到自己）
        /// </summary>
        private bool IsValidMove(Point position)
        {
            // 检查是否撞墙
            if (position.X < 0 || position.X >= gameController.Config.GameWidth ||
                position.Y < 0 || position.Y >= gameController.Config.GameHeight)
            {
                return false;
            }

            // 检查是否撞到自己
            foreach (var node in gameController.Snake.Body)
            {
                if (node.Position == position)
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 检查移动是否安全（考虑长蛇的情况）
        /// </summary>
        private bool IsSafeMove(Point position, Direction direction)
        {
            // 基本有效性检查
            if (!IsValidMove(position))
                return false;

            // 如果蛇身较短（≤5格），基本检查就足够了
            if (gameController.Snake.Body.Count <= 5)
                return true;

            // 对于长蛇，进行更深入的安全检查
            return IsMoveSafeForLongSnake(position, direction);
        }

        /// <summary>
        /// 检查长蛇的移动是否安全
        /// </summary>
        private bool IsMoveSafeForLongSnake(Point position, Direction direction)
        {
            // 模拟蛇移动后的状态
            var simulatedSnake = new List<Point>();
            
            // 添加新的头部位置
            simulatedSnake.Add(position);
            
            // 添加蛇身（除了尾部，因为蛇会移动）
            for (int i = 0; i < gameController.Snake.Body.Count - 1; i++)
            {
                simulatedSnake.Add(gameController.Snake.Body[i].Position);
            }

            // 检查移动后是否还有足够的空间
            return HasEnoughSpace(simulatedSnake, position);
        }

        /// <summary>
        /// 检查蛇是否有足够的移动空间
        /// </summary>
        private bool HasEnoughSpace(List<Point> snakeBody, Point headPosition)
        {
            // 计算蛇身占用的区域
            int minX = snakeBody.Min(p => p.X);
            int maxX = snakeBody.Max(p => p.X);
            int minY = snakeBody.Min(p => p.Y);
            int maxY = snakeBody.Max(p => p.Y);

            // 计算可用空间
            int availableWidth = maxX - minX + 1;
            int availableHeight = maxY - minY + 1;
            int snakeLength = snakeBody.Count;

            // 如果蛇身长度接近可用空间，需要更仔细检查
            if (snakeLength >= availableWidth * availableHeight * 0.7)
            {
                // 检查是否有足够的出口路径
                return HasEscapePath(headPosition, snakeBody);
            }

            return true;
        }

        /// <summary>
        /// 检查是否有逃生路径
        /// </summary>
        private bool HasEscapePath(Point headPosition, List<Point> snakeBody)
        {
            // 使用简单的BFS检查是否有足够的空间
            var visited = new HashSet<Point>();
            var queue = new Queue<Point>();
            queue.Enqueue(headPosition);
            visited.Add(headPosition);

            int accessibleCells = 0;
            int maxSearchDepth = Math.Min(10, gameController.Config.GameWidth * gameController.Config.GameHeight / 4);

            while (queue.Count > 0 && accessibleCells < maxSearchDepth)
            {
                Point current = queue.Dequeue();
                accessibleCells++;

                // 检查四个方向
                Direction[] directions = { Direction.Up, Direction.Down, Direction.Left, Direction.Right };
                foreach (Direction dir in directions)
                {
                    Point nextPos = GetNextPosition(current, dir);
                    
                    // 检查边界
                    if (nextPos.X < 0 || nextPos.X >= gameController.Config.GameWidth ||
                        nextPos.Y < 0 || nextPos.Y >= gameController.Config.GameHeight)
                        continue;

                    // 检查是否已访问或与蛇身重叠
                    if (visited.Contains(nextPos) || snakeBody.Contains(nextPos))
                        continue;

                    visited.Add(nextPos);
                    queue.Enqueue(nextPos);
                }
            }

            // 如果可访问的单元格数量足够多，认为有逃生路径
            return accessibleCells >= Math.Max(5, snakeBody.Count / 2);
        }

        /// <summary>
        /// 检查新位置是否更接近食物
        /// </summary>
        private bool IsCloserToFood(Point newPosition, Point foodPosition, Point currentPosition)
        {
            int currentDistance = Math.Abs(currentPosition.X - foodPosition.X) + Math.Abs(currentPosition.Y - foodPosition.Y);
            int newDistance = Math.Abs(newPosition.X - foodPosition.X) + Math.Abs(newPosition.Y - foodPosition.Y);
            return newDistance < currentDistance;
        }

        /// <summary>
        /// 游戏状态改变事件
        /// </summary>
        private void GameController_GameStateChanged(object sender, EventArgs e)
        {
            UpdateUI();
            UpdateGameTimer();
        }

        /// <summary>
        /// 得分改变事件
        /// </summary>
        private void GameController_ScoreChanged(object sender, EventArgs e)
        {
            UpdateScoreDisplay();
        }

        /// <summary>
        /// 游戏结束事件
        /// </summary>
        private void GameController_GameOver(object sender, EventArgs e)
        {
            gameTimer.Stop();
            demoTimer.Stop();
            isGameRunning = false;
            bool wasDemoMode = isDemoMode; // 保存演示模式状态
            isDemoMode = false;
            UpdateUI();
            
            // 只有在非演示模式下才检查是否进入排行榜
            if (!wasDemoMode && gameController.IsScoreQualifiedForLeaderboard())
            {
                string playerName = GetPlayerName();
                if (!string.IsNullOrEmpty(playerName))
                {
                    gameController.AddScoreToLeaderboard(playerName);
                    MessageBox.Show($"恭喜！您的分数已进入排行榜！\n玩家: {playerName}\n得分: {gameController.CurrentScore}", 
                                  "进入排行榜", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            
            // 显示游戏结束对话框
            string message = $"游戏结束！\n最终得分: {gameController.CurrentScore}\n最高分: {gameController.HighScore}";
            DialogResult result = MessageBox.Show(message, "游戏结束", MessageBoxButtons.OK, MessageBoxIcon.Information);
            
            // 游戏结束后不自动开始，让用户手动选择
        }

        /// <summary>
        /// 获取玩家姓名
        /// </summary>
        private string GetPlayerName()
        {
            using (var inputForm = new PlayerNameInputForm())
            {
                if (inputForm.ShowDialog() == DialogResult.OK)
                {
                    return inputForm.PlayerName;
                }
            }
            return "";
        }

        /// <summary>
        /// 更新游戏定时器
        /// </summary>
        private void UpdateGameTimer()
        {
            gameTimer.Interval = gameController.Config.GameSpeed;
        }

        /// <summary>
        /// 更新界面
        /// </summary>
        private void UpdateUI()
        {
            // 更新游戏状态标签
            string stateText = gameController.GetGameStateText();
            if (isDemoMode)
            {
                stateText += " (演示模式)";
            }
            lblGameState.Text = stateText;

            // 更新按钮状态
            bool isPlaying = gameController.State == GameState.Playing;
            bool isPaused = gameController.State == GameState.Paused;

            btnStart.Enabled = !isPlaying && !isPaused;
            btnPause.Enabled = isPlaying || isPaused;
            btnPause.Text = isPaused ? "继续" : "暂停";
            btnRestart.Enabled = true;

            // 更新演示模式按钮
            if (isDemoMode && isPlaying)
            {
                btnDemo.Text = "停止演示";
                btnDemo.BackColor = Color.Orange;
            }
            else
            {
                btnDemo.Text = "演示模式";
                btnDemo.BackColor = Color.Blue;
            }
            btnDemo.Enabled = !isPaused;

            // 更新菜单项状态
            startGameMenuItem.Enabled = !isPlaying && !isPaused;
            pauseGameMenuItem.Enabled = isPlaying || isPaused;
            pauseGameMenuItem.Text = isPaused ? "继续" : "暂停";
            restartGameMenuItem.Enabled = true;

            // 更新难度菜单项
            UpdateDifficultyMenuItems();
        }

        /// <summary>
        /// 更新难度菜单项
        /// </summary>
        private void UpdateDifficultyMenuItems()
        {
            easyMenuItem.Checked = gameController.Difficulty == GameDifficulty.Easy;
            mediumMenuItem.Checked = gameController.Difficulty == GameDifficulty.Medium;
            hardMenuItem.Checked = gameController.Difficulty == GameDifficulty.Hard;
        }

        /// <summary>
        /// 更新得分显示
        /// </summary>
        private void UpdateScoreDisplay()
        {
            lblCurrentScore.Text = $"得分: {gameController.CurrentScore}";
            lblHighScore.Text = $"最高分: {gameController.HighScore}";
        }

        /// <summary>
        /// 开始游戏
        /// </summary>
        private void StartGame()
        {
            gameController.StartGame();
            gameTimer.Start();
            isGameRunning = true;
            isDemoMode = false;
            gamePanel.Focus();
        }

        /// <summary>
        /// 开始演示模式
        /// </summary>
        private void StartDemo()
        {
            gameController.StartGame();
            demoTimer.Start();
            isGameRunning = true;
            isDemoMode = true;
            gamePanel.Focus();
        }

        /// <summary>
        /// 暂停/继续游戏
        /// </summary>
        private void TogglePause()
        {
            if (gameController.State == GameState.Playing)
            {
                gameController.PauseGame();
                gameTimer.Stop();
                demoTimer.Stop();
            }
            else if (gameController.State == GameState.Paused)
            {
                gameController.ResumeGame();
                if (isDemoMode)
                {
                    demoTimer.Start();
                }
                else
                {
                    gameTimer.Start();
                }
            }
        }

        /// <summary>
        /// 重新开始游戏
        /// </summary>
        private void RestartGame()
        {
            gameTimer.Stop();
            demoTimer.Stop();
            gameController.RestartGame();
            if (isDemoMode)
            {
                demoTimer.Start();
            }
            else
            {
                gameTimer.Start();
            }
            isGameRunning = true;
            gamePanel.Focus();
        }

        /// <summary>
        /// 游戏面板绘制事件
        /// </summary>
        private void gamePanel_Paint(object sender, PaintEventArgs e)
        {
            // 使用双缓冲绘制，避免闪烁
            RenderGame();
        }

        /// <summary>
        /// 窗体键盘事件
        /// </summary>
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Space:
                    if (gameController.State == GameState.NotStarted)
                    {
                        StartGame();
                    }
                    break;

                case Keys.D:
                    if (gameController.State == GameState.NotStarted || gameController.State == GameState.GameOver)
                    {
                        StartDemo();
                    }
                    break;

                case Keys.P:
                    TogglePause();
                    break;

                case Keys.R:
                    RestartGame();
                    break;

                case Keys.Up:
                case Keys.W:
                    if (!isDemoMode)
                    {
                        gameController.ChangeSnakeDirection(Direction.Up);
                    }
                    break;

                case Keys.Down:
                case Keys.S:
                    if (!isDemoMode)
                    {
                        gameController.ChangeSnakeDirection(Direction.Down);
                    }
                    break;

                case Keys.Left:
                case Keys.A:
                    if (!isDemoMode)
                    {
                        gameController.ChangeSnakeDirection(Direction.Left);
                    }
                    break;

                case Keys.Right:
                    if (!isDemoMode)
                    {
                        gameController.ChangeSnakeDirection(Direction.Right);
                    }
                    break;
            }
        }

        #region 按钮事件处理

        private void btnStart_Click(object sender, EventArgs e)
        {
            StartGame();
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            TogglePause();
        }

        private void btnRestart_Click(object sender, EventArgs e)
        {
            RestartGame();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        /// 演示模式按钮点击事件
        /// </summary>
        private void btnDemo_Click(object sender, EventArgs e)
        {
            if (gameController.State == GameState.NotStarted || gameController.State == GameState.GameOver)
            {
                StartDemo();
            }
            else if (gameController.State == GameState.Playing && isDemoMode)
            {
                // 如果已经在演示模式，则停止演示
                demoTimer.Stop();
                isDemoMode = false;
                UpdateUI();
            }
        }

        /// <summary>
        /// 排行榜按钮点击事件
        /// </summary>
        private void btnLeaderboard_Click(object sender, EventArgs e)
        {
            ShowLeaderboard();
        }

        /// <summary>
        /// 显示排行榜
        /// </summary>
        private void ShowLeaderboard()
        {
            using (var leaderboardForm = new LeaderboardForm(gameController.Leaderboard))
            {
                leaderboardForm.ShowDialog(this);
            }
        }

        #endregion

        #region 菜单事件处理

        private void startGameMenuItem_Click(object sender, EventArgs e)
        {
            StartGame();
        }

        private void pauseGameMenuItem_Click(object sender, EventArgs e)
        {
            TogglePause();
        }

        private void restartGameMenuItem_Click(object sender, EventArgs e)
        {
            RestartGame();
        }

        private void leaderboardMenuItem_Click(object sender, EventArgs e)
        {
            ShowLeaderboard();
        }

        private void exitMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void easyMenuItem_Click(object sender, EventArgs e)
        {
            gameController.SetDifficulty(GameDifficulty.Easy);
            UpdateDifficultyMenuItems();
        }

        private void mediumMenuItem_Click(object sender, EventArgs e)
        {
            gameController.SetDifficulty(GameDifficulty.Medium);
            UpdateDifficultyMenuItems();
        }

        private void hardMenuItem_Click(object sender, EventArgs e)
        {
            gameController.SetDifficulty(GameDifficulty.Hard);
            UpdateDifficultyMenuItems();
        }

        private void showGridMenuItem_Click(object sender, EventArgs e)
        {
            gameRenderer.ShowGrid = !gameRenderer.ShowGrid;
            showGridMenuItem.Checked = gameRenderer.ShowGrid;
            gamePanel.Invalidate();
        }

        private void aboutMenuItem_Click(object sender, EventArgs e)
        {
            string aboutText = "贪吃蛇游戏 v1.0\n\n" +
                              "操作说明：\n" +
                              "方向键或WASD：控制蛇的移动\n" +
                              "空格键：开始游戏\n" +
                              "D键：开始演示模式\n" +
                              "P键：暂停/继续\n" +
                              "R键：重新开始\n\n" +
                              "演示模式：\n" +
                              "点击演示模式按钮或按D键启动\n" +
                              "AI会自动控制蛇寻找食物\n" +
                              "再次点击按钮可停止演示\n\n" +
                              "游戏规则：\n" +
                              "控制蛇吃食物，避免撞墙和撞到自己\n" +
                              "每吃一个食物得10分\n" +
                              "连续吃3个食物有额外奖励\n\n" +
                              "开发者：AI Assistant\n" +
                              "开发时间：2024年";

            MessageBox.Show(aboutText, "关于游戏", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        #endregion

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            UpdateScoreDisplay();
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (gameTimer != null)
            {
                gameTimer.Stop();
                gameTimer.Dispose();
            }
            
            if (demoTimer != null)
            {
                demoTimer.Stop();
                demoTimer.Dispose();
            }
            
            // 释放双缓冲资源
            bufferedGraphics?.Dispose();
            
            // 释放渲染器资源
            gameRenderer?.Dispose();
            
            base.OnFormClosing(e);
        }

        /// <summary>
        /// 窗体大小改变事件
        /// </summary>
        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            
            // 重新初始化双缓冲以适应新的窗体大小
            if (gamePanel != null && gamePanel.Width > 0 && gamePanel.Height > 0)
            {
                bufferedGraphics?.Dispose();
                InitializeBufferedGraphics();
            }
        }
    }
}
